package org.ruanjj.multithread.JUC;

import java.util.Hashtable;
import java.util.concurrent.locks.ReentrantReadWriteLock;

//独占锁/共享锁 ReentrantReadWriteLock
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        CatchTable catchTable = new CatchTable();
        for (int i = 0; i < 5; i++) {
            final int n = i;
            new Thread(()->{
                catchTable.write(n+"名", n);
            }).start();
        }


        for (int i = 0; i < 5; i++) {
            final int n = i;
            new Thread(()->{
                catchTable.read(n+"名");
            }).start();
        }
    }
}


class CatchTable{
    private volatile Hashtable <String,Object> catchTable  = new Hashtable<>();
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public Object read(String key){
        try{
            lock.readLock().lock();
            System.out.println(Thread.currentThread().getName()+"正在读取。。。"+key);
            Object result = catchTable.get(key);
            System.out.println(Thread.currentThread().getName()+"读取完成");
            return result;
        }finally {
            lock.readLock().unlock();
        }
    }

    public void write(String key, Object o){
        try {
            lock.writeLock().lock();
            System.out.println(Thread.currentThread().getName()+"正在写入。。。"+key);
            catchTable.put(key,o);
            System.out.println(Thread.currentThread().getName()+"写入完成。。。。");
        }finally {
            lock.writeLock().unlock();
        }
    }
}
